/**
 * 
 */
package com.baidu.yun.push.model;

import java.util.List;

import cn.jpush.api.report.ReceivedsResult;
import cn.jpush.api.report.ReceivedsResult.Received;

import com.baidu.yun.core.log.YunLogEvent;
import com.baidu.yun.core.log.YunLogHandler;
import com.baidu.yun.push.auth.PushKeyPair;
import com.baidu.yun.push.client.BaiduPushClient;
import com.baidu.yun.push.constants.BaiduPushConstants;
import com.baidu.yun.push.exception.PushClientException;
import com.baidu.yun.push.exception.PushServerException;
import com.icbc.cte.base.CTEConstance;
import com.icbc.cte.base.TranFailException;
import com.icbc.cte.logging.Log;
import com.icbc.cte.logging.LogFactory;
import com.icbc.ctp.core.IContext;
import com.icbc.ctp.core.annotations.Input;
import com.icbc.ctp.core.annotations.JavaStep;
import com.icbc.ctp.core.annotations.Output;
import com.icbc.ctp.core.impl.OperationStep;

/**
 * TODO 类的描述：。 
 * <pre>
 *
 * </pre>
 *
 * <pre>
 * modify by lenovo on 2016-6-20
 *    fix->1.
 *         2.
 * </pre> 
 */
@Input(name = {  "pushId","divType" }, type = {  "String","String" }, description = { "","" }, mustInput = { true,true}, isVariable = { true,true })
@Output(name = {  "succnum" }, type = {  "String" }, description = { ""  })
@JavaStep
public class QueryMsgStatus extends OperationStep{
	 
	private static Log log = LogFactory.getCtpLog(QueryMsgStatus.class);

	@Override
	protected int execute(IContext context) throws TranFailException {
		String pushId = (String) getInputValue(context, "pushId");
//		JGPushUtil pushUtil=new JGPushUtil();
//		ReceivedsResult result=pushUtil.getSuccessNum(pushId);
////		System.out.println("送达数"+result);
//		List<Received> received_list=result.received_list;
//		int tmp	=received_list.get(0).android_received+received_list.get(0).ios_apns_sent;
		
//		System.out.println("送达数"+tmp);
//		// TODO Auto-generated method stub
//		String pushId = (String) getInputValue(context, "pushId");
//		int divType = Integer.parseInt((String) getInputValue(context, "divType"));
//		String[] msgIds = { pushId };
//		int num= pushAllMessage(msgIds, divType);
		
		setOutputValue(context,"succnum", "");
		return 0;
	}
	/**
	* 初始化百度推送
	* @return
	*/
	public static BaiduPushClient initPushClient(int divType){

		String apiKey = "";
		String secretKey = "";
		
		if(divType == 4){
			apiKey = CTEConstance.getEnvProperty("apiKeyIos");
			secretKey = CTEConstance.getEnvProperty("secretKeyIos"); 
		}else if(divType == 3){
			apiKey = CTEConstance.getEnvProperty("apiKey");
			secretKey = CTEConstance.getEnvProperty("secretKey"); 
		}
		
		PushKeyPair pair = new PushKeyPair(apiKey,secretKey);
	
		BaiduPushClient pushClient = new BaiduPushClient(pair,BaiduPushConstants.CHANNEL_REST_URL);
		pushClient.setChannelLogHandler(new YunLogHandler() {

			@Override
			public void onHandle(YunLogEvent arg0) {
			System.out.println(arg0.getMessage());

			}
			});
			return pushClient;
			}
	//广播
	public static int pushAllMessage(String[] msgId, int divType){
			
			BaiduPushClient client=initPushClient(divType);
			
			Integer sum=0;
			
			try {
				QueryMsgStatusRequest request=new QueryMsgStatusRequest();
				request.setMsgIds(msgId);
				request.setDeviceType(divType);
				
				QueryMsgStatusResponse  response=client.queryMsgStatus(request);
				
				
				
				 // Http请求返回值解析
	            System.out.println("totalNum: " + response.getTotalNum() + "\n"
	                    + "result:");
	            if (null != response) {
	                List<?> list = response.getMsgSendInfos();
	                for (int i = 0; i < list.size(); i++) {
	                    Object object = list.get(i);
	                    if (object instanceof MsgSendInfo) {
	                        MsgSendInfo msgSendInfo = (MsgSendInfo) object;
	                        StringBuilder strBuilder = new StringBuilder();
	                        strBuilder.append("List[" + i + "]: {" + "msgId = "
	                                + msgSendInfo.getMsgId() + ",status = "
	                                + msgSendInfo.getMsgStatus() + ",sendTime = "
	                                + msgSendInfo.getSendTime() + ",successCount = "
	                                + msgSendInfo.getSuccessCount());
	                        strBuilder.append("}\n");
	                        System.out.println(strBuilder.toString());
	                        	
	                        	sum=msgSendInfo.getSuccessCount();
	                    }
	                }
	            }

			} catch (PushClientException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (PushServerException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			if (sum == null) {
				log.error("sum is null");
				sum = -1;
			}
			return sum;

	}
	//广播
	public static int[] pushAllMessage0(String[] msgId, int[] divType){
			
			
			int[] sum=null;
			
			for(int i=0; i<divType.length;i++){
				String[] s ={msgId[i]};
				
				sum[i++]=pushAllMessage(s,divType[i]);
			}
			
			if (sum == null) {
				log.error("sum is null");
				sum = null;
			}
			return sum;

	}
	public static void main(String[] args) {
		String[] msgIds = { "5666079104460773812" };
		pushAllMessage(msgIds, 4);//3：Android，4：IOS
	}
}
